<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Season Detail</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body, html { background: #18181a !important; color: #fff; overflow-x: hidden; }
        .season-bg {
            position: relative;
            width: 100vw;
            height: 100vh;
            background: #222;
            overflow: hidden;
        }
        .season-bg-img {
            width: 100vw;
            height: 100vh;
            object-fit: cover;
            filter: brightness(0.55);
        }
        .season-bg-overlay {
            position: absolute; left: 0; top: 0; width: 100%; height: 100%;
            background: linear-gradient(90deg, #18181a 0%, #18181aa0 40%, #18181a00 100%);
        }
        .season-main-info {
            position: absolute; left: 0; top: 0; width: 100%; height: 100%;
            display: flex; flex-direction: column; justify-content: center; padding-left: 80px; z-index: 2;
        }
        .season-title {
            font-size: 2.6em; font-weight: bold; letter-spacing: 0.01em; margin-bottom: 10px;
            max-width: 65vw;
            word-break: break-word;
            margin-right: 32px;
        }
        .season-meta { color: #eee; font-size: 1.1em; margin-bottom: 10px; }
        .season-desc {
            color: #ccc; font-size: 1.08em; max-width: 700px; margin-bottom: 18px;
            display: -webkit-box;
            -webkit-line-clamp: 4;
            -webkit-box-orient: vertical;
            overflow: hidden;
            position: relative;
            transition: max-height 0.2s;
        }
        .season-desc.expanded {
            -webkit-line-clamp: unset;
            max-height: none;
            overflow: visible;
        }
        #descMoreBtn {
            background: none;
            border: none;
            color: #4ea3ff;
            font-size: 1em;
            cursor: pointer;
            margin-top: 4px;
            margin-left: 0;
            padding: 0;
            display: none;
        }
        .season-platforms { display: flex; gap: 12px; margin-bottom: 18px; }
        .season-platform-btn { background: #222; border: none; border-radius: 8px; padding: 8px 16px; color: #fff; font-size: 1.1em; display: flex; align-items: center; gap: 8px; transition: background 0.2s; }
        .season-platform-btn img { width: 32px; height: 32px; border-radius: 6px; }
        .season-platform-btn:hover { background: #444; }
        .season-section { margin: 0 auto; max-width: 1400px; padding: 0 40px; }
        .season-tabs { display: flex; gap: 32px; margin-top: 32px; margin-bottom: 12px; }
        .season-tab { color: #ccc; font-size: 1.2em; cursor: pointer; padding: 4px 18px; border-radius: 8px; transition: background 0.2s, color 0.2s; }
        .season-tab.active { color: #fff; background: #222; font-weight: bold; }
        .episodes-list, .cast-list, .bonus-list, .morelike-list {
            display: flex; gap: 18px; overflow-x: auto; padding-bottom: 8px; margin-bottom: 18px;
            scrollbar-width: thin; scrollbar-color: #444 #222;
        }
        .episodes-list::-webkit-scrollbar, .cast-list::-webkit-scrollbar, .bonus-list::-webkit-scrollbar, .morelike-list::-webkit-scrollbar {
            height: 8px; background: #222; border-radius: 6px;
        }
        .episodes-list::-webkit-scrollbar-thumb, .cast-list::-webkit-scrollbar-thumb, .bonus-list::-webkit-scrollbar-thumb, .morelike-list::-webkit-scrollbar-thumb {
            background: #444; border-radius: 6px;
        }
        .episodes-list::-webkit-scrollbar-thumb:hover, .cast-list::-webkit-scrollbar-thumb:hover, .bonus-list::-webkit-scrollbar-thumb:hover, .morelike-list::-webkit-scrollbar-thumb:hover {
            background: #666;
        }
        .episode-item { width: 400px; min-width: 400px; background: #222; border-radius: 12px; overflow: hidden; margin-bottom: 8px; cursor: pointer; transition: box-shadow 0.18s, transform 0.18s; }
        .episode-item img { width: 100%; height: 225px; object-fit: cover; }
        .episode-title { color: #fff; font-size: 1em; font-weight: 500; padding: 8px 12px 0 12px; }
        .moreseasons-title { color: #fff; font-size: 1.1em; font-weight: bold; margin: 18px 0 8px 0; }
        .moreseasons-list {
            display: flex; gap: 18px; margin-bottom: 18px;
            overflow-x: auto; padding-bottom: 8px;
            scrollbar-width: thin; scrollbar-color: #444 #222;
        }
        .moreseasons-list::-webkit-scrollbar {
            height: 8px; background: #222; border-radius: 6px;
        }
        .moreseasons-list::-webkit-scrollbar-thumb {
            background: #444; border-radius: 6px;
        }
        .moreseasons-list::-webkit-scrollbar-thumb:hover {
            background: #666;
        }
        .moreseasons-item { width: 300px; min-width: 300px; background: #222; border-radius: 14px; overflow: hidden; cursor: pointer; transition: transform 0.18s; }
        .moreseasons-item img { width: 100%; height: 400px; object-fit: cover; border-radius: 14px 14px 0 0; }
        .moreseasons-title-text { color: #fff; font-size: 1em; font-weight: 500; padding: 8px 8px 6px 8px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .cast-item { text-align: center; width: 110px; }
        .cast-img { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; margin-bottom: 8px; border: 2px solid #333; }
        .cast-name { color: #fff; font-size: 1em; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .cast-role { color: #aaa; font-size: 0.95em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .bonus-item { width: 260px; min-width: 260px; background: #181818; border-radius: 12px; overflow: hidden; margin-bottom: 8px; }
        .bonus-img { width: 100%; height: 140px; object-fit: cover; }
        .bonus-title { color: #fff; font-size: 1em; font-weight: 500; padding: 8px 12px 0 12px; }
        .bonus-desc { color: #bbb; font-size: 0.97em; padding: 0 12px 8px 12px; }
        .bonus-duration { color: #aaa; font-size: 0.92em; padding: 0 12px 8px 12px; }
        .morelike-title { color: #fff; font-size: 0.98em; font-weight: 500; padding: 8px 8px 6px 8px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        @media (max-width: 900px) {
            .season-main-info { padding-left: 24px; }
            .season-section { padding: 0 10px; }
        }
    </style>
</head>
<body>
    <div class="season-bg">
        <img class="season-bg-img" id="seasonBgImg" src="" alt="">
        <div class="season-bg-overlay"></div>
        <div class="season-main-info">
            <div id="seasonAward" style="color:#ffd700;font-size:1.1em;margin-bottom:6px;"></div>
            <div class="season-title" id="seasonTitle">Season Title</div>
            <div class="season-meta" id="seasonMeta"></div>
            <div class="season-desc" id="seasonDesc"></div>
            <div class="season-platforms" id="seasonPlatforms"></div>
        </div>
    </div>
    <div class="season-section">
        <div class="season-tabs">
            <div class="season-tab active" id="tabEpisodes">Episodes</div>
            <div class="season-tab" id="tabCast">Cast & Crew</div>
            <div class="season-tab" id="tabBonus">Bonuses</div>
        </div>
        <div id="episodesSection">
            <div class="episodes-list" id="episodesList"></div>
            <div class="moreseasons-title">More Seasons</div>
            <div class="moreseasons-list" id="moreSeasonsList"></div>
            <div class="moreseasons-title">More Like This</div>
            <div class="morelike-list" id="morelikeList"></div>
        </div>
        <div id="castSection" style="display:none;">
            <div class="cast-list" id="castList"></div>
            <div class="moreseasons-title">More Seasons</div>
            <div class="moreseasons-list" id="moreSeasonsList2"></div>
            <div class="moreseasons-title">More Like This</div>
            <div class="morelike-list" id="morelikeList2"></div>
        </div>
        <div id="bonusSection" style="display:none;">
            <div class="bonus-list" id="bonusList"></div>
            <div class="moreseasons-title">More Seasons</div>
            <div class="moreseasons-list" id="moreSeasonsList3"></div>
            <div class="moreseasons-title">More Like This</div>
            <div class="morelike-list" id="morelikeList3"></div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // ========== 工具 ==========
    function getQueryParam(name) {
        const url = window.location.search;
        const params = new URLSearchParams(url);
        return params.get(name);
    }
    function buildApiUrl(token, value) {
        return `https://saas.zeasn.tv/sp/api/device/v1/column/resourceDetail?token=${encodeURIComponent(token)}&resourceType=12&value=${encodeURIComponent(value)}&needPoster=true&posterWidth=1280&needAward=true&moreFields=bonuses`;
    }
    // ========== 数据加载 ==========
    async function loadSeasonDetail() {
        const token = getQueryParam('token');
        const value = getQueryParam('value');
        let userToken = localStorage.getItem('userToken');
        if (!userToken) userToken = '';
        if (!token || !value) {
            $('#seasonTitle').text('参数缺失，无法加载季详情');
            return;
        }
        const API_URL = buildApiUrl(token, value);
        let currentSeasonId = '';
        let currentSourceId = '';
        let currentValue = value;
        let deeplinkList = [];
        try {
            const res = await fetch(API_URL);
            const data = await res.json();
            if (!data.data) {
                $('#seasonTitle').text('未获取到季详情');
                return;
            }
            const d = data.data;
            // 获取当前季id，使用字符串处理避免精度丢失
            try {
                const decodedValue = decodeURIComponent(value);
                // 使用正则表达式提取 id，避免 JSON.parse 精度丢失
                const idMatch = decodedValue.match(/"id":(\d+)/);
                if (idMatch) {
                    currentSeasonId = idMatch[1]; // 直接使用字符串，不转换为数字
                } else {
                    currentSeasonId = String(d.id);
                }
                currentValue = typeof value === 'string' ? value : JSON.stringify(value);
            } catch(e) { 
                currentSeasonId = String(d.id); 
            }
            // 平台按钮
            $('#seasonPlatforms').empty();
            deeplinkList = Array.isArray(d.deeplinks) ? d.deeplinks : [];
            if (deeplinkList.length > 0) {
                deeplinkList.forEach((link, idx) => {
                    const icon = link.sourceIcon || '';
                    const name = link.sourceName || '';
                    const sid = link.sourceId || '';
                    const btn = $(`<button class='season-platform-btn' data-sourceid='${sid}'>${icon ? `<img src='${icon}'>` : ''}<span>${name}</span></button>`);
                    if (idx === 0) btn.addClass('active');
                    btn.on('click', async function() {
                        $('.season-platform-btn').removeClass('active');
                        $(this).addClass('active');
                        currentSourceId = sid;
                        $('#episodesList').empty();
                        await loadEpisodesByApi(token, userToken, currentSourceId, currentValue);
                    });
                    $('#seasonPlatforms').append(btn);
                });
                // 默认用第一个播放源sourceId
                currentSourceId = deeplinkList[0].sourceId || '';
            } else {
                currentSourceId = d.sourceId || '';
            }
            // 顶部大图
            const poster = (d.posters && d.posters[0] && d.posters[0].url) || (d.covers && d.covers[0] && d.covers[0].url) || '';
            $('#seasonBgImg').attr('src', poster);
            // 奖项
            if (Array.isArray(d.awardInfo) && d.awardInfo.length > 0) {
                $('#seasonAward').text(d.awardInfo.map(a => a.name).join(' / '));
            } else {
                $('#seasonAward').text('');
            }
            // 标题
            $('#seasonTitle').text(d.name || '');
            // meta
            let metaArr = [];
            if (Array.isArray(d.categories) && d.categories.length > 0) metaArr.push(d.categories.map(c=>c.name).join(' / '));
            if (d.releaseTime) {
                const dt = new Date(Number(d.releaseTime));
                if (!isNaN(dt.getTime())) metaArr.push(dt.getFullYear());
            }
            if (Array.isArray(d.scores) && d.scores.length > 0) metaArr.push(d.scores.map(s=>`${s.type}: ${s.value}`).join(' / '));
            if (d.episodeCount) metaArr.push(`${d.episodeCount} Episodes`);
            if (d.originLangs && d.originLangs.length > 0) metaArr.push(d.originLangs.join(', '));
            if (d.ratings && d.ratings.length > 0) metaArr.push('Rated: ' + d.ratings.join(','));
            if (d.ratingTag) metaArr.push(`<span class='badge bg-secondary'>${d.ratingTag}</span>`);
            $('#seasonMeta').html(metaArr.join(' • '));
            // 简介
            let descText = d.description || '';
            function renderDescWithBtn(desc, expanded) {
                const btnText = expanded ? 'less' : 'more';
                return desc + ` <span id=\"descMoreBtn\" style=\"color:#4ea3ff;cursor:pointer;\">${btnText}</span>`;
            }
            function handleDescCollapse() {
                const $desc = $('#seasonDesc');
                $desc.data('full', descText);
                function update(expanded) {
                    $desc.toggleClass('expanded', expanded);
                    if (expanded) {
                        $desc.html(renderDescWithBtn(descText, true));
                    } else {
                        $desc.html(renderDescWithBtn(descText, false));
                    }
                }
                setTimeout(() => {
                    $desc.html(renderDescWithBtn(descText, false));
                    if ($desc[0].scrollHeight > $desc[0].clientHeight + 5) {
                        $desc.on('click', '#descMoreBtn', function() {
                            update(!$desc.hasClass('expanded'));
                        });
                    } else {
                        $desc.html(descText);
                    }
                }, 100);
            }
            handleDescCollapse();
            // Episodes（通过新接口获取）
            $('#episodesList').empty();
            await loadEpisodesByApi(token, userToken, currentSourceId, currentValue);
            // Bonuses
            $('#bonusList').empty();
            if (Array.isArray(d.bonuses) && d.bonuses.length > 0) {
                d.bonuses.forEach(bonus => {
                    const img = bonus.poster || bonus.icon || '';
                    const title = bonus.name || '';
                    const id = bonus.id || '';
                    // 时长格式化
                    let durationStr = '';
                    if (bonus.duration) {
                        let d = Number(bonus.duration);
                        if (!isNaN(d) && d > 0) {
                            const h = Math.floor(d / 3600);
                            const m = Math.floor((d % 3600) / 60);
                            const s = d % 60;
                            let arr = [];
                            if (h > 0) arr.push(h + 'h');
                            if (m > 0) arr.push(m + 'm');
                            if (s > 0 || arr.length === 0) arr.push(s + 's');
                            durationStr = arr.join(' ');
                        }
                    }
                    // 播放源
                    let sourceStr = '';
                    if (Array.isArray(bonus.deeplinkDetailList) && bonus.deeplinkDetailList.length > 0) {
                        sourceStr = `<div style='display:flex;gap:10px;flex-wrap:wrap;padding:0 12px 2px 12px;'>` +
                            bonus.deeplinkDetailList.map(link =>
                                `<div style='display:flex;align-items:center;gap:4px;background:#181818;padding:2px 8px 2px 2px;border-radius:6px;'>`+
                                (link.sourceIcon ? `<img src='${link.sourceIcon}' style='width:22px;height:22px;border-radius:4px;'>` : '')+
                                `<span style='color:#fff;font-size:0.97em;'>${link.sourceName||''}</span>`+
                                `<span style='color:#aaa;font-size:0.85em;'>#${link.sourceId||''}</span>`+
                                `</div>`
                            ).join('') + `</div>`;
                    }
                    $('#bonusList').append(`
                        <div class='bonus-item' style='background:#222;border-radius:10px;width:300px;min-width:300px;overflow:hidden;margin-bottom:12px;'>
                            <img class='bonus-img' src='${img}' alt='${title}' style='width:100%;height:180px;object-fit:cover;'>
                            <div class='bonus-title' style='font-size:1.1em;font-weight:bold;padding:8px 12px 0 12px;'>${title}</div>
                            <div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${durationStr}</div>
                            <div style='color:#bbb;font-size:0.92em;padding:0 12px 2px 12px;'>ID: ${id}</div>
                            ${sourceStr}
                        </div>
                    `);
                });
            }
            // Cast & Crew
            $('#castList').empty();
            if (Array.isArray(d.casts) && d.casts.length > 0) {
                d.casts.forEach(cast => {
                    const castId = cast.id || cast.castId || '';
                    let valueParam = '';
                    if (cast.value) {
                        if (typeof cast.value === 'object') {
                            valueParam = encodeURIComponent(JSON.stringify(cast.value));
                        } else {
                            valueParam = encodeURIComponent(cast.value);
                        }
                    } else {
                        valueParam = encodeURIComponent(JSON.stringify({id: castId, objectType: 'PEOPLE'}));
                    }
                    const tokenParam = encodeURIComponent(token);
                    const $item = $(
                        `<div class='cast-item' style='cursor:pointer;'>
                            <img class='cast-img' src='${cast.coverImg||''}' alt='${cast.name||''}'>
                            <div class='cast-name'>${cast.name||''}</div>
                            <div class='cast-role'>${cast.type||''}</div>
                            <div style="color:#bbb;font-size:0.92em;word-break:break-all;">${cast.value ? cast.value : ''}</div>
                        </div>`
                    );
                    $item.on('click', function() {
                        if (castId || cast.value) {
                            window.open(`people-detail.html?token=${tokenParam}&value=${valueParam}`, '_blank');
                        }
                    });
                    $('#castList').append($item);
                });
            }
            // More Like This
            loadMoreLikeThis(token, value);
            // More Seasons（推荐：详情加载后再调，保证参数完整）
            await loadMoreSeasons(token, userToken, value);
        } catch (e) {
            $('#seasonTitle').text('加载失败');
        }
    }
    async function loadMoreLikeThis(token, seasonValue) {
        $('#morelikeList, #morelikeList2, #morelikeList3').empty().append('<div style="color:#aaa;padding:32px 0;">Loading...</div>');
        if (!token || !seasonValue) return;
        let seasonId = '';
        try {
            // 智能解码：尝试多次解码直到无法继续
            let decodedValue = seasonValue;
            let decodeCount = 0;
            const maxDecodes = 3;
            while (decodeCount < maxDecodes) {
                try {
                    const testDecode = decodeURIComponent(decodedValue);
                    if (testDecode === decodedValue) {
                        break;
                    }
                    decodedValue = testDecode;
                    decodeCount++;
                } catch(e) {
                    break;
                }
            }
            // 方法1: 尝试直接解析 JSON
            try {
                const parsed = JSON.parse(decodedValue);
                if (parsed && parsed.id !== undefined) {
                    seasonId = String(parsed.id);
                }
            } catch(jsonError) {
                // 方法2: 尝试正则表达式提取
                let idMatch = decodedValue.match(/"id":\s*(\d+)/);
                if (!idMatch) {
                    idMatch = decodedValue.match(/"id"\s*:\s*(\d+)/);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/id["\s]*:["\s]*(\d+)/);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/id["\s]*:["\s]*[\"]*(\d+)[\"]*/);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/id["\s]*:["\s]*(\d+)/i);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/"id":\s*"?(\d+)"?/);
                }
                if (idMatch) {
                    seasonId = idMatch[1];
                }
            }
            if (!seasonId) {
                console.error('无法从 seasonValue 中提取 id');
                // 备用方案：尝试从URL中直接提取数字作为ID
                const urlMatch = window.location.search.match(/[?&]value=([^&]+)/);
                if (urlMatch) {
                    const urlValue = urlMatch[1];
                    const numberMatch = urlValue.match(/(\d+)/);
                    if (numberMatch) {
                        seasonId = numberMatch[1];
                    }
                }
                if (!seasonId) {
                    $('#morelikeList, #morelikeList2, #morelikeList3').html('<div style="color:#ff6666;padding:32px 0;">Unable to extract episode ID</div>');
                    return;
                }
            }
        } catch(e) {
            console.error('解析 seasonValue 失败:', e);
            $('#morelikeList, #morelikeList2, #morelikeList3').html('<div style="color:#ff6666;padding:32px 0;">Failed to parse episode parameters</div>');
            return;
        }
        const url = `https://saas.zeasn.tv/sp/api/device/v1/video/recommend?token=${encodeURIComponent(token)}&videoType=SEASON&size=10&needPoster=true&imgStyle=1&videoId=${encodeURIComponent(seasonId)}`;
        try {
            const res = await fetch(url);
            const data = await res.json();
            if (!data.data || !Array.isArray(data.data) || data.data.length === 0) {
                $('#morelikeList, #morelikeList2, #morelikeList3').html('<div style="color:#aaa;padding:32px 0;">暂无推荐</div>');
                return;
            }
            $('#morelikeList, #morelikeList2, #morelikeList3').empty();
            data.data.forEach(item => {
                const img = item.poster || item.icon || '';
                const title = item.name || '';
                // categories 展示
                let categoriesStr = '';
                if (item.moreInfo && Array.isArray(item.moreInfo.categories) && item.moreInfo.categories.length > 0) {
                    categoriesStr = `<div style='color:#ffb84d;font-size:0.97em;padding:0 12px 2px 12px;'>${item.moreInfo.categories.map(c => c.name).join(' / ')}</div>`;
                } else if (Array.isArray(item.categories) && item.categories.length > 0) {
                    categoriesStr = `<div style='color:#ffb84d;font-size:0.97em;padding:0 12px 2px 12px;'>${item.categories.join(' / ')}</div>`;
                }
                // videoScores 展示
                let videoScoresStr = '';
                if (item.moreInfo && Array.isArray(item.moreInfo.videoScores) && item.moreInfo.videoScores.length > 0) {
                    videoScoresStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${item.moreInfo.videoScores.map(vs => `${vs.type||''}: ${vs.value||''}`).join(' / ')}</div>`;
                } else if (Array.isArray(item.videoScores) && item.videoScores.length > 0) {
                    videoScoresStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${item.videoScores.map(vs => `${vs.name||''}: ${vs.score||''}`).join(' / ')}</div>`;
                }
                // seasonNumber / episodeCount 展示（仅SEASON类型）
                let seasonNumber = '';
                let episodeCount = '';
                if (item.seasonNumber !== undefined) {
                    seasonNumber = item.seasonNumber;
                } else if (item.moreInfo && item.moreInfo.seasonNumber !== undefined) {
                    seasonNumber = item.moreInfo.seasonNumber;
                } else if (item.value) {
                    try {
                        const v = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                        if (v.seasonNumber !== undefined) seasonNumber = v.seasonNumber;
                    } catch(e){}
                }
                if (item.episodeCount !== undefined) {
                    episodeCount = item.episodeCount;
                } else if (item.moreInfo && item.moreInfo.episodeCount !== undefined) {
                    episodeCount = item.moreInfo.episodeCount;
                } else if (item.value) {
                    try {
                        const v = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                        if (v.episodeCount !== undefined) episodeCount = v.episodeCount;
                    } catch(e){}
                }
                let isSeasonType = (item.objectType === 'SEASON' || (item.value && typeof item.value === 'object' && item.value.objectType === 'SEASON'));
                let seasonInfoStr = '';
                if (isSeasonType && (seasonNumber || episodeCount)) {
                    let arr = [];
                    if (seasonNumber) arr.push('S' + seasonNumber);
                    if (episodeCount) arr.push(episodeCount + ' episodes');
                    seasonInfoStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${arr.join(' / ')}</div>`;
                }
                // duration 展示
                let duration = '';
                if (item.duration !== undefined) {
                    duration = item.duration;
                } else if (item.moreInfo && item.moreInfo.duration !== undefined) {
                    duration = item.moreInfo.duration;
                } else if (item.value) {
                    try {
                        const v = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                        if (v.duration !== undefined) duration = v.duration;
                    } catch(e){}
                }
                function formatDuration(d) {
                    d = Number(d);
                    if (isNaN(d) || d <= 0) return '';
                    const h = Math.floor(d / 3600);
                    const m = Math.floor((d % 3600) / 60);
                    const s = d % 60;
                    let arr = [];
                    if (h > 0) arr.push(h + 'h');
                    if (m > 0) arr.push(m + 'm');
                    if (s > 0 || arr.length === 0) arr.push(s + 's');
                    return arr.join(' ');
                }
                let durationStr = '';
                if (duration) {
                    durationStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${formatDuration(duration)}</div>`;
                }
                // value展示
                const valueStr = item.value ? `<div style='color:#bbb;font-size:0.92em;word-break:break-all;padding:0 12px 2px 12px;'>${item.value}</div>` : '';
                // deeplinkDetailList展示
                let deeplinkHtml = '';
                if (Array.isArray(item.deeplinkDetailList) && item.deeplinkDetailList.length) {
                    deeplinkHtml = `<div style='display:flex;gap:10px;flex-wrap:wrap;padding:0 12px 8px 12px;'>` +
                        item.deeplinkDetailList.map(link =>
                            `<div style='display:flex;align-items:center;gap:4px;background:#181818;padding:2px 8px 2px 2px;border-radius:6px;'>`+
                            (link.sourceIcon ? `<img src='${link.sourceIcon}' style='width:22px;height:22px;border-radius:4px;'>` : '')+
                            `<span style='color:#fff;font-size:0.97em;'>${link.sourceName||''}</span>`+
                            `<span style='color:#aaa;font-size:0.85em;'>#${link.sourceId||''}</span>`+
                            `</div>`
                        ).join('') + `</div>`;
                }
                // releaseTime 展示（格式化）
                let releaseTimeStr = '';
                if (item.releaseTime) {
                    const d = new Date(Number(item.releaseTime));
                    if (!isNaN(d.getTime())) {
                        const y = d.getFullYear();
                        const m = (d.getMonth()+1).toString().padStart(2,'0');
                        const day = d.getDate().toString().padStart(2,'0');
                        releaseTimeStr = `<div style='color:#6cf;font-size:0.92em;padding:0 12px 2px 12px;'>${y}-${m}-${day}</div>`;
                    }
                }
                // 卡片结构调整为 movie-detail.html 的 morelike-item
                const $item = $(
                    `<div class="morelike-item" tabindex="0" style="background:#222;border-radius:10px;width:300px;min-width:300px;overflow:hidden;cursor:pointer;transition:transform 0.18s;">
                        <img src="${img}" alt="${title}" style="width:100%;height:400px;object-fit:cover;">
                        <div class="morelike-title">${title}</div>
                        ${categoriesStr}${videoScoresStr}
                        <div style='text-align:left;'>
                            ${seasonInfoStr}
                            ${durationStr}
                            ${releaseTimeStr}
                            ${valueStr}${deeplinkHtml}
                        </div>
                    </div>`
                );
                // 跳转到详情页
                $item.on('click', function() {
                    let valueStrParam = item.value ? (typeof item.value === 'string' ? item.value : JSON.stringify(item.value)) : '';
                    window.open(`season-detail.html?token=${encodeURIComponent(token)}&value=${encodeURIComponent(valueStrParam)}`, '_blank');
                });
                $('#morelikeList, #morelikeList2, #morelikeList3').append($item);
            });
        } catch (e) {
            $('#morelikeList, #morelikeList2, #morelikeList3').html('<div style="color:#aaa;padding:32px 0;">加载失败</div>');
        }
    }
    // 新增：通过接口获取episodes
    async function loadEpisodesByApi(token, userToken, sourceId, value) {
        if (!token || !sourceId || !value) return;
        const url = `https://saas.zeasn.tv/sp/api/device/v1/episode?token=${encodeURIComponent(token)}&userToken=${encodeURIComponent(userToken)}&sourceId=${encodeURIComponent(sourceId)}&startIndex=0&iconShape=HORIZONTAL&iconWidth=&iconHeight=&moreFields=duration&value=${encodeURIComponent(value)}&size=30`;
        try {
            const res = await fetch(url);
            const data = await res.json();
            if (!data.data || !Array.isArray(data.data.dataList) || data.data.dataList.length === 0) {
                $('#episodesList').html('<div style="color:#aaa;padding:32px 0;">No episodes</div>');
                return;
            }
            // 获取当前平台名和icon
            let $activeBtn = $('.season-platform-btn.active');
            let platformName = $activeBtn.find('span').text() || '';
            let platformIcon = $activeBtn.find('img').attr('src') || '';
            data.data.dataList.forEach(ep => {
                const img = ep.poster || ep.icon || 'data:image/svg+xml;utf8,<svg width=\"220\" height=\"124\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"220\" height=\"124\" fill=\"%23333\"/><text x=\"50%\" y=\"50%\" fill=\"%23999\" font-size=\"18\" font-family=\"Arial\" text-anchor=\"middle\" alignment-baseline=\"middle\">No Image</text></svg>';
                const title = ep.name || '';
                // 时长格式化
                let durationStr = '';
                if (ep.duration) {
                    let d = Number(ep.duration);
                    if (!isNaN(d) && d > 0) {
                        const h = Math.floor(d / 3600);
                        const m = Math.floor((d % 3600) / 60);
                        const s = d % 60;
                        let arr = [];
                        if (h > 0) arr.push(h + 'h');
                        if (m > 0) arr.push(m + 'm');
                        if (s > 0 || arr.length === 0) arr.push(s + 's');
                        durationStr = arr.join(' ');
                    }
                }
                // 播放源
                let sourceStr = platformIcon ? `<img src='${platformIcon}' style='width:22px;height:22px;vertical-align:middle;margin-right:6px;border-radius:4px;'>` : '';
                sourceStr += `<span style='vertical-align:middle;'>${platformName}</span>`;
                $('#episodesList').append(`
                    <div class='episode-item'>
                        <img src='${img}' alt='${title}'>
                        <div class='episode-title'>${title}</div>
                        <div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${durationStr}</div>
                        <div style='color:#6cf;font-size:0.92em;padding:0 12px 8px 12px;display:flex;align-items:center;gap:6px;'>${sourceStr}</div>
                    </div>
                `);
            });
        } catch (e) {
            $('#episodesList').html('<div style="color:#aaa;padding:32px 0;">加载失败</div>');
        }
    }
    async function loadMoreSeasons(token, userToken, seasonValue) {
        const $lists = $('#moreSeasonsList, #moreSeasonsList2, #moreSeasonsList3');
        $lists.empty().append('<div style="color:#aaa;padding:32px 0;">Loading...</div>');
        if (!token || !seasonValue) {
            return;
        }
        // 智能解码：尝试多次解码直到无法继续
        let seasonId = '';
        try {
            let decodedValue = seasonValue;
            let decodeCount = 0;
            const maxDecodes = 3;
            while (decodeCount < maxDecodes) {
                try {
                    const testDecode = decodeURIComponent(decodedValue);
                    if (testDecode === decodedValue) {
                        break;
                    }
                    decodedValue = testDecode;
                    decodeCount++;
                } catch(e) {
                    break;
                }
            }
            // 方法1: 尝试直接解析 JSON
            try {
                const parsed = JSON.parse(decodedValue);
                if (parsed && parsed.id !== undefined) {
                    seasonId = String(parsed.id);
                }
            } catch(jsonError) {
                // 方法2: 尝试正则表达式提取
                let idMatch = decodedValue.match(/"id":\s*(\d+)/);
                if (!idMatch) {
                    idMatch = decodedValue.match(/"id"\s*:\s*(\d+)/);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/id["\s]*:["\s]*(\d+)/);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/id["\s]*:["\s]*[\"]*(\d+)[\"]*/);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/id["\s]*:["\s]*(\d+)/i);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/"id":\s*"?(\d+)"?/);
                }
                if (idMatch) {
                    seasonId = idMatch[1];
                }
            }
            if (!seasonId) {
                console.error('无法从 seasonValue 中提取 id');
                // 备用方案：尝试从URL中直接提取数字作为ID
                const urlMatch = window.location.search.match(/[?&]value=([^&]+)/);
                if (urlMatch) {
                    const urlValue = urlMatch[1];
                    const numberMatch = urlValue.match(/(\d+)/);
                    if (numberMatch) {
                        seasonId = numberMatch[1];
                    }
                }
                if (!seasonId) {
                    $lists.html('<div style="color:#ff6666;padding:32px 0;">Unable to extract episode ID</div>');
                    return;
                }
            }
        } catch(e) {
            console.error('解析 seasonValue 失败:', e);
            $lists.html('<div style="color:#ff6666;padding:32px 0;">Failed to parse episode parameters</div>');
            return;
        }
        const url = `https://saas.zeasn.tv/whaletime/api/whalemeta/v1/season/related/${encodeURIComponent(seasonId)}?token=${encodeURIComponent(token)}&userToken=${encodeURIComponent(userToken)}&moreInfo=true&coverWidth=&coverHeight=`;
        try {
            const res = await fetch(url);
            const data = await res.json();
            if (!data.data || !Array.isArray(data.data) || data.data.length === 0) {
                $lists.html('<div style="color:#aaa;padding:32px 0;">暂无相关季</div>');
                return;
            }
            $lists.empty();
            data.data.forEach(item => {
                const img = item.cover || '';
                const title = item.name || '';
                // 分类
                let categoriesStr = '';
                if (item.moreInfo && Array.isArray(item.moreInfo.categories) && item.moreInfo.categories.length > 0) {
                    categoriesStr = `<div style='color:#ffb84d;font-size:0.97em;padding:0 12px 2px 12px;'>${item.moreInfo.categories.map(c => c.name).join(' / ')}</div>`;
                }
                // 集数
                let episodeCountStr = '';
                if (item.moreInfo && item.moreInfo.episodeCount) {
                    episodeCountStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${item.moreInfo.episodeCount} episodes</div>`;
                }
                // 年份
                let yearStr = '';
                if (item.moreInfo && item.moreInfo.releaseYear) {
                    yearStr = `<div style='color:#6cf;font-size:0.92em;padding:0 12px 2px 12px;'>${item.moreInfo.releaseYear}</div>`;
                }
                // 评分
                let scoresStr = '';
                if (item.moreInfo && Array.isArray(item.moreInfo.scores) && item.moreInfo.scores.length > 0) {
                    scoresStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${item.moreInfo.scores.map(s => `${s.type||''}: ${s.value||''}`).join(' / ')}</div>`;
                }
                // value
                const valueStr = item.value ? `<div style='color:#bbb;font-size:0.92em;word-break:break-all;padding:0 12px 2px 12px;'>${item.value}</div>` : '';
                // 卡片结构
                const $item = $(`
                    <div class="morelike-item" tabindex="0" style="background:#222;border-radius:10px;width:300px;min-width:300px;overflow:hidden;cursor:pointer;transition:transform 0.18s;">
                        <img src="${img}" alt="${title}" style="width:100%;height:400px;object-fit:cover;">
                        <div class="morelike-title">${title}</div>
                        ${categoriesStr}${scoresStr}
                        <div style='text-align:left;'>
                            ${episodeCountStr}
                            ${yearStr}
                            ${valueStr}
                        </div>
                    </div>
                `);
                $item.on('click', function() {
                    let valueStrParam = item.value ? (typeof item.value === 'string' ? item.value : JSON.stringify(item.value)) : '';
                    window.open(`season-detail.html?token=${encodeURIComponent(token)}&value=${encodeURIComponent(valueStrParam)}`, '_blank');
                });
                $lists.append($item);
            });
        } catch (e) {
            $lists.html('<div style="color:#aaa;padding:32px 0;">加载失败</div>');
        }
    }
    $(function(){
        // 页面初始直接解析参数，先请求more seasons
        const token = getQueryParam('token');
        const value = getQueryParam('value');
        let userToken = localStorage.getItem('userToken');
        if (!userToken) userToken = '';
        if (token && value) {
            loadMoreSeasons(token, userToken, value);
        }
        loadSeasonDetail();
        // Tab 切换
        $('#tabEpisodes').on('click', function(){
            $('#tabEpisodes').addClass('active');
            $('#tabCast').removeClass('active');
            $('#tabBonus').removeClass('active');
            $('#episodesSection').show();
            $('#castSection').hide();
            $('#bonusSection').hide();
        });
        $('#tabCast').on('click', function(){
            $('#tabCast').addClass('active');
            $('#tabEpisodes').removeClass('active');
            $('#tabBonus').removeClass('active');
            $('#episodesSection').hide();
            $('#castSection').show();
            $('#bonusSection').hide();
        });
        $('#tabBonus').on('click', function(){
            $('#tabBonus').addClass('active');
            $('#tabEpisodes').removeClass('active');
            $('#tabCast').removeClass('active');
            $('#episodesSection').hide();
            $('#castSection').hide();
            $('#bonusSection').show();
        });
        // 鼠标滚轮横向滚动
        $('.episodes-list, .cast-list, .bonus-list, .morelike-list').on('wheel', function(e) {
            if (e.originalEvent.deltaY === 0) return;
            this.scrollLeft += e.originalEvent.deltaY;
            e.preventDefault();
        });
        // moreseasons-list 也支持横向滚动
        $('.moreseasons-list').on('wheel', function(e) {
            if (e.originalEvent.deltaY === 0) return;
            this.scrollLeft += e.originalEvent.deltaY;
            e.preventDefault();
        });
    });
    </script>
</body>
</html> 